package com.qf.leadnewsbehavior.interceptors;

import com.qf.leadnewsutils.commons.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class HeaderInterceptor implements HandlerInterceptor {

    //请求到达处理器之前执行的方法
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的uid信息
        String uid = request.getHeader("uid");

        //存入ThreadLocal对象
        ThreadLocalUtil.saveUid(Long.parseLong(uid));
        return true;
    }

    //处理器方法执行完后，一定会执行的（不管正常执行还是异常执行）
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //从ThreadLocal中将uid信息移除（防止内存泄露）
        ThreadLocalUtil.removeUid();
    }
}
